﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CollabXT.Generator
{
    public partial class MainForm : Form
    {
        private String tfsDirectory;

        public String ScaffoldingDirectory
        {
            get { return tfsDirectory; }
            set { tfsDirectory = value;
                this.textTFS.Text = value;
            }
        }
        private String vmxtDirectory;

        public String VMXTDirectory
        {
            get { return vmxtDirectory; }
            set { vmxtDirectory = value;
                this.textVMXT.Text = value;
            }
        }
        private String targetDirectory;

        public String TargetDirectory
        {
            get { return targetDirectory; }
            set { targetDirectory = value;
                this.textTarget.Text = value;
            }
        }
        private String xmlFile;
        private String cssFile;
        private const string executable = "\\vmxt2tfs.exe";
        delegate void SetTextCallback(string text);
        IntegrationEventArgs integrationData;
        WizardForm wizard;

        public MainForm()
        {
            InitializeComponent();
            this.processVMXT2TFS.StartInfo.FileName = System.IO.Directory.GetCurrentDirectory() + executable;
            this.processVMXT2TFS.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(processVMXT2TFS_OutputReceived);
            this.processVMXT2TFS.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(processVMXT2TFS_OutputReceived);
            wizard = new WizardForm();
            wizard.Integrated +=new IntegrationEventHandler(wizard_Integrated);
            integrationData = null;
            
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
        }

        private void processVMXT2TFS_OutputReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                logText(String.Format("{0}\n",e.Data));
                if (this.stsLabelProgess.Value<95)
                {
                    this.stsLabelProgess.Value +=1 ;
                }
            }
        }

        private void processVMXT2TFS_Exited(object sender, EventArgs e)
        {
            logText("\nGenerator ended.");
            this.stsLabelText.Text = "Generator ended. See Log for more Information.";
            if (processVMXT2TFS.ExitCode != 0)
            {
                logText("\nThere were errors:\n");
                this.stsLabelText.Text = "Generator ended with errors. See Log for more Information.";
            }
            processVMXT2TFS.CancelErrorRead();
            processVMXT2TFS.CancelOutputRead();
            reactivateGeneration();
        }
        
        private void vmxtBrowse_Click(object sender, EventArgs e)
        {
            if (this.folderBrowser.ShowDialog() == DialogResult.OK)
            {
                VMXTDirectory = this.folderBrowser.SelectedPath;
            }
        }

        private void tfsBrowse_Click(object sender, EventArgs e)
        {
            if (this.folderBrowser.ShowDialog() == DialogResult.OK )
            {
                ScaffoldingDirectory = this.folderBrowser.SelectedPath;
                this.checkIntegration.Checked = false;
                integrationData = null;
                this.textIntegrated.Text = "There is no integrated Microprocess";
                
                if (File.Exists(Path.Combine(ScaffoldingDirectory,"vmxt_style.css")))
                {
                    cssFile = Path.Combine(ScaffoldingDirectory, "vmxt_style.css");
                    this.textCSS.Text = cssFile;
                }
            }
        }

        private void targetBrowse_Click(object sender, EventArgs e)
        {
            if (this.folderBrowser.ShowDialog() == DialogResult.OK)
            {
                TargetDirectory = this.folderBrowser.SelectedPath;
            }
           
        }

        private void buttonGenerate_Click(object sender, EventArgs e)
        {
            this.Log.Text = "";
            this.buttonGenerate.Enabled = false;
            this.stsLabelProgess.Increment(10);
            logText("Starting generator\n");
            this.stsLabelText.Text = "Starting generator...";
            string tfsSource = ScaffoldingDirectory;
            if (checkIntegration.Checked && integrationData!=null)
            {
                tfsSource = integrationData.IntegratedScaffolding.FullName;
            }
            String arguments = String.Format("--no-file -t \"{0}\" -v \"{1}\" -x \"{2}\" --css \"{3}\" \"{4}\"",
                tfsSource,VMXTDirectory,xmlFile,cssFile,TargetDirectory);
            if (this.debugToolStripMenuItem.Checked)
            {
                arguments += " -d";
            }
            logText(String.Format("Using {0}\n", this.processVMXT2TFS.StartInfo.FileName));
            this.processVMXT2TFS.StartInfo.Arguments = arguments;
            logText("Generator arguments " + arguments + " \n");
            try
            {
                this.processVMXT2TFS.Start();
                processVMXT2TFS.BeginOutputReadLine();
                processVMXT2TFS.BeginErrorReadLine();
            }
            catch(Exception ex)
            {
                logText(String.Format("Could not start vmxt2tfs process:{0}",ex.Message));
                this.stsLabelText.Text = "Generator ended with errors. See Log for more Information.";
                reactivateGeneration();
                return;
            }
            logText("Generator started\n");
        }
        
        private void reactivateGeneration()
        {
            this.stsLabelProgess.Value = 100;
            this.buttonGenerate.Enabled = true;
            this.tabMain.SelectTab(1);
        }
        
        private void xmlBrowse_Click(object sender, EventArgs e)
        {
            this.openXMLFile.InitialDirectory = this.folderBrowser.SelectedPath;
            if (this.openXMLFile.ShowDialog() == DialogResult.OK)
            {
                xmlFile = this.openXMLFile.FileName;
                this.textXMLexport.Text = xmlFile;
            }
        }

        private void textTFS_TextChanged(object sender, EventArgs e)
        {
            ScaffoldingDirectory = this.textTFS.Text;
            if (File.Exists(Path.Combine(ScaffoldingDirectory, "vmxt_style.css")))
            {
                cssFile = Path.Combine(ScaffoldingDirectory, "vmxt_style.css");
                this.textCSS.Text = cssFile;
            }
        }

        private void textXMLexport_TextChanged(object sender, EventArgs e)
        {
            xmlFile = this.textXMLexport.Text;
        }

        private void textVMXT_TextChanged(object sender, EventArgs e)
        {
            VMXTDirectory = this.textVMXT.Text;
        }

        private void textTarget_TextChanged(object sender, EventArgs e)
        {
            TargetDirectory = this.textTarget.Text;
        }

        private void buttonCSS_Click(object sender, EventArgs e)
        {
            this.openCSSFile.InitialDirectory = this.folderBrowser.SelectedPath;
            if (this.openCSSFile.ShowDialog() == DialogResult.OK)
            {
                cssFile = this.openCSSFile.FileName;
                this.textCSS.Text = cssFile;
            }   
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void integrateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            startWizard();
        }
        
        private void wizard_Integrated(object o, IntegrationEventArgs e)
        {
            textWITs.Clear();
            textQueries.Clear();
            textDocuLibs.Clear();
            this.textIntegrated.Text = String.Format("Integrated scaffolding generated at {0}",
                e.IntegratedScaffolding.FullName);
            this.checkIntegration.Checked = true;
            ScaffoldingDirectory = e.Scaffolding.FullName;
            integrationData = e;
            foreach(FileInfo f in integrationData.ScaffoldingWITs)
            {
                textWITs.AppendText(String.Format("{0}\r\n",f.Name));
            }
            foreach (FileInfo f in integrationData.MicroWITs)
            {
                textWITs.AppendText(String.Format("{0}\r\n", f.Name));
            }
            foreach (FileInfo f in integrationData.ScaffoldingQueries)
            {
                textQueries.AppendText(String.Format("{0}\r\n", f.Name));
            }
            foreach (FileInfo f in integrationData.MicroQueries)
            {
                textQueries.AppendText(String.Format("{0}\r\n", f.Name));
            }
            foreach (FileInfo f in integrationData.ScaffoldingReports)
            {
                textReports.AppendText(String.Format("{0}\r\n", f.Name));
            }
            foreach (FileInfo f in integrationData.MicroReports)
            {
                textReports.AppendText(String.Format("{0}\r\n", f.Name));
            }
            foreach (DirectoryInfo f in integrationData.Libraries)
            {
                textDocuLibs.AppendText(String.Format("{0}\r\n", f.Name));
            }
            this.tabMain.SelectTab(2);
            
        }
        
        private void logText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.Log.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(logText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.Log.AppendText(text);
            }
        }

        private void checkIntegration_CheckedChanged(object sender, EventArgs e)
        {
            if (checkIntegration.Checked == true)
                
            {
                if (integrationData == null)
                {
                    this.labelWarning.Visible = true;

                    startWizard();
                }
                else
                {
                    this.labelWarning.Visible = false;
                    this.textIntegrated.Text = String.Format("Integrated scaffolding generated at {0}",
            integrationData.IntegratedScaffolding.FullName);
                }
            }
            if (checkIntegration.Checked == false && integrationData != null)
            {
                textIntegrated.Text = "Integrated generation inactive. Activate through checkbox on generator page.";
            }
        }

        private void startWizard()
        {
            this.stsLabelText.Text = "Integrating micro process";
            //logText("Achtung: Mit dem Mergen eines Micro Prozesses verlieren Sie die V-Modell XT Konformität. Für eine spätere Konformitätsprüfung benötigen Sie in jedem Fall folgende Log Datei: vmxt2tfs-merge.log");
            logText("Attention: Merging a micro process will break V-Modell XT conformity. For a later conformity check you will need the vmxt2tfs-merge.log file");
            this.stsLabelProgess.Value = 0;
            wizard.Scaffolding = ScaffoldingDirectory;
            wizard.Reset();
            wizard.ShowDialog(this);
            this.stsLabelText.Text = "Ready";
            if (checkIntegration.Checked == true && integrationData == null)
            {
                checkIntegration.Checked = false;
            }
        }
    }
}